'use client'

import { useState, useEffect } from 'react'
import { useRouter, useParams } from 'next/navigation'
import { 
  XMarkIcon, 
  PlusIcon, 
  ChevronDownIcon, 
  ChevronRightIcon, 
  FolderIcon, 
  ArchiveBoxIcon 
} from '@heroicons/react/24/outline'
import NewProjectModal from './NewProjectModal'

interface User {
  id: number
  name: string
  email: string
  color: string
  avatar?: string
}

interface Project {
  id: number
  name: string
  description: string
  isArchived: boolean
  created_at: string
}

interface ProjectSidebarProps {
  isOpen: boolean
  onClose: () => void
  currentProjectName?: string
  showNewProjectButton?: boolean
  onNewProjectClick?: () => void
  showBackToDashboard?: boolean
}

export default function ProjectSidebar({
  isOpen,
  onClose,
  currentProjectName,
  showNewProjectButton = true,
  onNewProjectClick,
  showBackToDashboard = true
}: ProjectSidebarProps) {
  const router = useRouter()
  const params = useParams()
  const [projects, setProjects] = useState<Project[]>([])
  const [currentUser, setCurrentUser] = useState<User | null>(null)
  const [isNewProjectModalOpen, setIsNewProjectModalOpen] = useState(false)
  const [expandedSections, setExpandedSections] = useState({
    currentProjects: true,
    archivedProjects: false
  })

  useEffect(() => {
    fetchProjects()
    fetchCurrentUser()
  }, [])

  const fetchCurrentUser = async () => {
    try {
      const response = await fetch('/api/user/me')
      if (response.ok) {
        const user = await response.json()
        setCurrentUser(user)
      } else {
        const errorData = await response.json()
        if (errorData.casdoorError) {
          // Casdoor相关错误，显示用户友好的错误信息
          alert(`认证服务暂时不可用：${errorData.error}\n\n请检查网络连接或联系管理员。`)
          // 重定向到登录页面
          router.push('/auth/login')
        } else {
          // 其他错误
          console.error('获取当前用户失败:', errorData.error)
        }
      }
    } catch (err) {
      console.error('获取当前用户失败:', err)
      // 网络错误或其他异常
      alert('无法连接到服务器，请检查网络连接后重试。')
    }
  }

  const fetchProjects = async () => {
    try {
      const response = await fetch('/api/projects')
      if (response.ok) {
        const projectsData = await response.json()
        setProjects(projectsData)
      }
    } catch (err) {
      console.error('获取项目列表失败:', err)
    }
  }

  const handleArchiveProject = async (projectId: number, projectName: string, isArchived: boolean) => {
    const action = isArchived ? '归档' : '取消归档'
    if (confirm(`确定要${action}项目 "${projectName}" 吗？`)) {
      try {
        const response = await fetch(`/api/projects/${projectId}/archive`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ isArchived }),
        })
        if (response.ok) {
          // 更新项目列表中的归档状态
          const updatedProjects = projects.map(p => 
            p.id === projectId ? { ...p, isArchived } : p
          )
          setProjects(updatedProjects)
        } else {
          const data = await response.json()
          alert(data.error || `${action}项目失败`)
        }
      } catch (err) {
        console.error(`${action}项目失败:`, err)
        alert(`${action}项目失败，请重试`)
      }
    }
  }

  const handleDeleteProject = async (projectId: number, projectName: string) => {
    if (confirm(`确定要删除项目 "${projectName}" 吗？此操作不可恢复。`)) {
      try {
        const response = await fetch(`/api/projects/${projectId}`, {
          method: 'DELETE',
        })
        if (response.ok) {
          // 从列表中移除已删除的项目
          const updatedProjects = projects.filter(p => p.id !== projectId)
          setProjects(updatedProjects)
          
          // 如果删除的是当前项目，跳转到dashboard
          if (currentProjectName && projectName === currentProjectName) {
            router.push('/dashboard')
          }
        } else {
          const data = await response.json()
          alert(data.error || '删除项目失败')
        }
      } catch (err) {
        console.error('删除项目失败:', err)
        alert('删除项目失败，请重试')
      }
    }
  }

  const handleNewProjectSuccess = () => {
    setIsNewProjectModalOpen(false)
    fetchProjects() // 重新获取项目列表
  }

  return (
    <>
      <div className={`fixed inset-y-0 left-0 z-30 transform ${isOpen ? 'translate-x-0' : '-translate-x-full'} transition-transform duration-300 ease-in-out bg-gray-800 text-white w-64 space-y-6 py-7 px-2`}>
        <div className="flex items-center justify-between px-2">
          <span className="text-2xl font-semibold">项目列表</span>
          <button onClick={onClose} className="md:hidden text-white">
            <XMarkIcon className="h-6 w-6" />
          </button>
        </div>
        
        {showNewProjectButton && (
          <div className="px-2">
            <button
              onClick={() => {
                if (onNewProjectClick) {
                  onNewProjectClick()
                } else {
                  setIsNewProjectModalOpen(true)
                }
              }}
              className="w-full text-white font-bold py-2 px-4 rounded transition duration-150 ease-in-out flex items-center justify-center"
              style={{ 
                backgroundColor: currentUser?.color || '#4F46E5'
              }}
              onMouseEnter={(e) => {
                if (currentUser?.color) {
                  e.currentTarget.style.backgroundColor = `${currentUser.color}CC`
                }
              }}
              onMouseLeave={(e) => {
                if (currentUser?.color) {
                  e.currentTarget.style.backgroundColor = currentUser.color
                }
              }}
            >
              <PlusIcon className="h-5 w-5 mr-2" /> 新建项目
            </button>
          </div>
        )}
        
        <nav className="flex-1 overflow-y-auto">
          {/* 当前项目 */}
          <div className="mb-4">
            <button
              onClick={() => setExpandedSections(prev => ({ ...prev, currentProjects: !prev.currentProjects }))}
              className="flex items-center justify-between w-full px-4 py-2 text-left text-sm font-medium text-gray-300 hover:text-white hover:bg-gray-700 rounded transition-colors"
            >
              <div className="flex items-center">
                <FolderIcon className="h-4 w-4 mr-2" />
                <span>当前项目</span>
                <span className="ml-2 text-xs bg-gray-600 text-gray-300 px-2 py-1 rounded-full">
                  {projects.filter(p => !p.isArchived).length}
                </span>
              </div>
              {expandedSections.currentProjects ? (
                <ChevronDownIcon className="h-4 w-4" />
              ) : (
                <ChevronRightIcon className="h-4 w-4" />
              )}
            </button>
            
            {expandedSections.currentProjects && (
              <div className="ml-4 space-y-1">
                {projects.filter(p => !p.isArchived).map((proj) => (
                  <div
                    key={proj.id}
                    className="group relative flex items-center justify-between"
                  >
                    <a
                      href={`/${encodeURIComponent(proj.name)}/todolist`}
                      className={`block flex-1 py-2 px-4 rounded transition duration-200 hover:bg-gray-700 text-sm ${
                        proj.name === currentProjectName 
                          ? 'bg-gray-700 text-white' 
                          : ''
                      }`}
                    >
                      {proj.name}
                    </a>
                    <div className="absolute right-2 flex items-center space-x-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                      <button
                        onClick={(e) => {
                          e.preventDefault()
                          handleArchiveProject(proj.id, proj.name, true)
                        }}
                        className="p-1 rounded-full text-gray-400 hover:text-yellow-500 transition-colors"
                        title="归档项目"
                      >
                        <ArchiveBoxIcon className="h-4 w-4" />
                      </button>
                      <button
                        onClick={(e) => {
                          e.preventDefault()
                          handleDeleteProject(proj.id, proj.name)
                        }}
                        className="p-1 rounded-full text-gray-400 hover:text-red-500 transition-colors"
                        title="删除项目"
                      >
                        <XMarkIcon className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                ))}
                {projects.filter(p => !p.isArchived).length === 0 && (
                  <p className="text-gray-400 px-4 py-2 text-sm">暂无当前项目</p>
                )}
              </div>
            )}
          </div>

          {/* 归档项目 */}
          <div className="mb-4">
            <button
              onClick={() => setExpandedSections(prev => ({ ...prev, archivedProjects: !prev.archivedProjects }))}
              className="flex items-center justify-between w-full px-4 py-2 text-left text-sm font-medium text-gray-300 hover:text-white hover:bg-gray-700 rounded transition-colors"
            >
              <div className="flex items-center">
                <ArchiveBoxIcon className="h-4 w-4 mr-2" />
                <span>归档项目</span>
                <span className="ml-2 text-xs bg-gray-600 text-gray-300 px-2 py-1 rounded-full">
                  {projects.filter(p => p.isArchived).length}
                </span>
              </div>
              {expandedSections.archivedProjects ? (
                <ChevronDownIcon className="h-4 w-4" />
              ) : (
                <ChevronRightIcon className="h-4 w-4" />
              )}
            </button>
            
            {expandedSections.archivedProjects && (
              <div className="ml-4 space-y-1">
                {projects.filter(p => p.isArchived).map((proj) => (
                  <div
                    key={proj.id}
                    className="group relative flex items-center justify-between"
                  >
                    <a
                      href={`/${encodeURIComponent(proj.name)}/todolist`}
                      className={`block flex-1 py-2 px-4 rounded transition duration-200 hover:bg-gray-700 text-sm text-gray-400 ${
                        proj.name === currentProjectName 
                          ? 'bg-gray-700 text-white' 
                          : ''
                      }`}
                    >
                      {proj.name}
                    </a>
                    <div className="absolute right-2 flex items-center space-x-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                      <button
                        onClick={(e) => {
                          e.preventDefault()
                          handleArchiveProject(proj.id, proj.name, false)
                        }}
                        className="p-1 rounded-full text-gray-400 hover:text-green-500 transition-colors"
                        title="取消归档"
                      >
                        <FolderIcon className="h-4 w-4" />
                      </button>
                      <button
                        onClick={(e) => {
                          e.preventDefault()
                          handleDeleteProject(proj.id, proj.name)
                        }}
                        className="p-1 rounded-full text-gray-400 hover:text-red-500 transition-colors"
                        title="删除项目"
                      >
                        <XMarkIcon className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                ))}
                {projects.filter(p => p.isArchived).length === 0 && (
                  <p className="text-gray-400 px-4 py-2 text-sm">暂无归档项目</p>
                )}
              </div>
            )}
          </div>
        </nav>
        
        {showBackToDashboard && (
          <div className="absolute bottom-0 w-full px-2 pb-4">
            <button
              onClick={() => router.push('/dashboard')}
              className="w-full text-left py-2.5 px-4 rounded transition duration-200 hover:bg-gray-700"
            >
              返回仪表板
            </button>
          </div>
        )}
      </div>

      <NewProjectModal
        isOpen={isNewProjectModalOpen}
        onClose={() => setIsNewProjectModalOpen(false)}
        onSuccess={handleNewProjectSuccess}
      />
    </>
  )
} 